package com.lc.zpyh.ui.fragment.shopcar;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppFragment;
import com.lc.zpyh.http.glide.GlideApp;
import com.lc.zpyh.http.request.AddCartApi;
import com.lc.zpyh.http.request.CarApi;
import com.lc.zpyh.http.request.DeleteByIdsApi;
import com.lc.zpyh.http.request.PublicMsgBean;
import com.lc.zpyh.http.response.CarBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.supermarket.BusinessActivity;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.SPUtil;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

public class ShopCarFragment  extends AppFragment {
    private String id;
    private String checkTv;
    @BindView(R.id.rv_shop_order)
    RecyclerView recyclerView;
    @BindView(R.id.layout_refresh)
    TwinklingRefreshLayout refreshLayout;
    private BaseQuickAdapter adapter;
    List<CarBean.ListDTO> lds = new ArrayList<CarBean.ListDTO>();
    private int page= 1;
    public static ShopCarFragment newInstance(String id,String checkTv) {
        ShopCarFragment fragment = new ShopCarFragment();
        Bundle args = new Bundle();
        args.putString("id", id);
        args.putString("checkTv", checkTv);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getString("id");
            checkTv = getArguments().getString("checkTv");

            getOrderList();

        }
    }
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_car_list;
    }

    @Override
    protected void initView() {

    }

    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                page = 1;
                lds.clear();
                getOrderList();
                refreshLayout.finishRefreshing();

            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
//                page++;
//                getMoreOrderList();
                refreshLayout.finishRefreshing();
                refreshLayout.setEnableLoadmore(false);
            }
        });
    }
    private CarBean carBean;
    private  BaseQuickAdapter goodsAdp;
    private void getOrderList(){
        EasyHttp.post(this).api(new CarApi().setUserid(SPUtil.get(getContext(), IntentKey.USERID, ""))
                .setSchoolid(SPUtil.get(getContext(), IntentKey.ADDRESSID, ""))
                .setStid(id)
                .setPageNum(page+"")
                .setPageSize("1000")
                .setMerchantid(""))
                .request(new HttpCallback<CarBean>(this) {
                    @Override
                    public void onSucceed(CarBean data) {
                        carBean = data;
                        lds.addAll(data.getList());
                        for(int i =0;i<data.getList().size();i++){
                            data.getList().get(i).setAll(false);
                            for (int j=0;j<data.getList().get(i).getCarts().size();j++){
                                data.getList().get(i).getCarts().get(j).setAll(false);
                            }
                        }
//设置取消选择
                        callBackValue.SelectAll(false);
                        adapter = new BaseQuickAdapter<CarBean.ListDTO, BaseViewHolder>(R.layout.item_shop_car, data.getList()) {
                            @Override
                            protected void convert(BaseViewHolder baseViewHolder, final CarBean.ListDTO dataBean) {
                                      baseViewHolder.setText(R.id.shop_name,dataBean.getMerchantName());
                                      RelativeLayout linearLayout =baseViewHolder.getView(R.id.dy_layout);
                                      if(dataBean.getStatusa()!=0){
                                          baseViewHolder.setVisible(R.id.dy_layout,true);
//                                          linearLayout.setClickable(true);
                                      }else {
                                          baseViewHolder.setVisible(R.id.dy_layout,false);
//                                          linearLayout.setClickable(false);
                                      }
                                       //店铺复选框
                                        CheckBox checkBox =baseViewHolder.getView(R.id.all_check);
                                        checkBox.setChecked(dataBean.isAll());
                                        checkBox.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (dataBean.getStatusa() == 0 || checkTv.equals("删除")) {
                                                    if (dataBean.isAll()) {
                                                        dataBean.setAll(false);
                                                        for (int i = 0; i < dataBean.getCarts().size(); i++) {
                                                            dataBean.getCarts().get(i).setAll(false);
                                                        }
                                                    } else {
                                                        dataBean.setAll(true);
                                                        for (int i = 0; i < dataBean.getCarts().size(); i++) {
                                                            dataBean.getCarts().get(i).setAll(true);
                                                        }
                                                    }
                                                    callBackValue.SendMoney(data);
                                                    //刷新适配器
                                                    adapter.notifyItemChanged(baseViewHolder.getLayoutPosition());
                                                    goodsAdp.notifyDataSetChanged();
                                                    //检测最外层是否选中
                                                    callBackValue.SelectAll(getSelectAll());
                                                }
                                            }
                                        });
                                      RecyclerView rv_order_goods=baseViewHolder.getView(R.id.food_recy);
                                      goodsAdp =new BaseQuickAdapter<CarBean.CartsDTO, BaseViewHolder>(R.layout.item_car_shoppingcart,dataBean.getCarts()) {
                                             @Override
                                            protected void convert(@NotNull BaseViewHolder baseViewHolder, CarBean.CartsDTO bean) {
                                                CheckBox checkBox =baseViewHolder.getView(R.id.item_check);
                                                baseViewHolder.setText(R.id.goods,bean.getCommodityName());
                                                if(bean.getSpecificationId()==null){
                                                    baseViewHolder.setVisible(R.id.tv_yueshou,false);
                                                }else {
                                                    baseViewHolder.setVisible(R.id.tv_yueshou,true);
                                                    if (bean.getNameOne() != null) {
                                                        baseViewHolder.setText(R.id.tv_yueshou, bean.getNameOne());
                                                    }
                                                    if (bean.getNameTwo() != null) {
                                                        baseViewHolder.setText(R.id.tv_yueshou, bean.getNameOne() + "、" + bean.getNameTwo());
                                                    }

                                                }
                                                if(bean.getSpecificationId()==null){

                                                    baseViewHolder.setText(R.id.tv_xianjia,"￥"+ BigDecimalUtils.div(bean.getPrice()+"","100",2));
                                                }else {
                                                    baseViewHolder.setText(R.id.tv_xianjia,"￥"+BigDecimalUtils.div(bean.getPrice()+"","100",2));
                                                }
                                                baseViewHolder.setText(R.id.tv_number,bean.getCount()+"");
                                                //显示商品图片 判断是为了刷新时防止图片闪烁
                                                 ImageView iv =(ImageView) baseViewHolder.getView(R.id.img_dianpu);
                                                 String tag =(String)(iv.getTag());
                                                 if(!bean.getSpimg().equals(tag)){
                                                     iv.setTag(bean.getSpimg());
                                                     GlideApp.with(getActivity())
                                                             .load(IntentKey.CAR_IMAGE+bean.getSpimg())
                                                             .skipMemoryCache(false)
                                                             .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                                                             .into(iv);
                                                 }

                                               //加号
                                               baseViewHolder.getView(R.id.fl_add).setOnClickListener(new View.OnClickListener() {
                                                   @Override
                                                   public void onClick(View v) {
                                                       if (dataBean.getStatusa() == 0) {
                                                           //商品数量额增加
                                                           //接口处
                                                           int size = bean.getCount();
                                                           size++;
                                                           addShopCart(bean.getCommodityId() + "", "1", bean.getSpecificationId() + "", bean.getPrice() + "", bean.getCondimentsId() + "", dataBean.getMerchantid() + "", bean, baseViewHolder, size);
                                                           //以下部分调用接口后然后成功，放入success中，会更改数量和结算价格


                                                           //核算价格和运费

                                                           ///////////////////////////////////////////////////////
                                                       }
                                                   }
                                                 });
                                                 //减号
                                                 baseViewHolder.getView(R.id.fl_reduce).setOnClickListener(new View.OnClickListener() {
                                                     @Override
                                                     public void onClick(View v) {
                                                         //商品数量额减少
                                                         //接口处
                                                         if (dataBean.getStatusa() == 0) {
                                                             //以下部分调用接口后然后成功，放入success中，会更改数量和结算价格
                                                             int size = bean.getCount();
                                                             if (size > 1) {
                                                                 size--;
                                                                 bean.setCount(size);
                                                                 addShopCart(bean.getCommodityId() + "", "-1", bean.getSpecificationId() + "", bean.getPrice() + "", bean.getCondimentsId() + "", dataBean.getMerchantid() + "", bean, baseViewHolder, size);

//                                                             baseViewHolder.setText(R.id.tv_number,size+"");
                                                             } else {
                                                                 deleteByIds(bean.getCartId() + "");
                                                             }
                                                             //核算价格和运费
                                                             callBackValue.SendMoney(data);
                                                             //////////////////////////////////////////////////////////
                                                         }
                                                     }
                                                 });
                                                 checkBox.setChecked(bean.isAll());
                                                 checkBox.setOnClickListener(new View.OnClickListener() {
                                                     @Override
                                                     public void onClick(View v) {
                                                         if (dataBean.getStatusa() == 0 || checkTv.equals("删除")) {
                                                             bean.setAll(!bean.isAll());
                                                             num = 0;
                                                             for (int i = 0; i < dataBean.getCarts().size(); i++) {
                                                                 if (dataBean.getCarts().get(i).isAll()) {
                                                                     num++;
                                                                 }
                                                             }
                                                             if (num == dataBean.getCarts().size()) {
                                                                 dataBean.setAll(true);
                                                                 adapter.notifyDataSetChanged();
                                                             }
                                                             if (dataBean.isAll()) {
                                                                 if (num == 0 || num < dataBean.getCarts().size()) {
                                                                     dataBean.setAll(false);
                                                                     adapter.notifyDataSetChanged();
                                                                 }
                                                             }
                                                             //核算价格和运费
                                                             callBackValue.SendMoney(data);
                                                             //刷新适配器
                                                             goodsAdp.notifyItemChanged(baseViewHolder.getPosition(), "ASDASD");
                                                             //检测最外层是否选中
                                                             callBackValue.SelectAll(getSelectAll());
                                                         }
                                                     }
                                                 });

                                             }
                                    };



                                     rv_order_goods.setAdapter(goodsAdp);
                                ((BaseQuickAdapter<CarBean.CartsDTO, BaseViewHolder>) rv_order_goods.getAdapter()).setOnItemClickListener((baseQuickAdapter, view, i) -> {
                                    if (dataBean.getStatusa() == 0) {
                                        startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id", dataBean.getMerchantid() + ""));
                                    }

                                });
                            }
                        };
                        View emptyview = View.inflate(getContext(), R.layout.empty_emptylayout, null);

                        adapter.setEmptyView(emptyview);
                        recyclerView.setAdapter(adapter);
                        callBackValue.SendMoney(data);
                    }
                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);

                    }
                });
    }

    private void addShopCart(String id,String count,String specificationId,String price,String condimentsId,String merchantid, CarBean.CartsDTO bean,BaseViewHolder baseViewHolder,int size) {


        EasyHttp.post(this)
                .api(new AddCartApi().setUserId(SPUtil.get(getContext(),IntentKey.USERID,"")).setCount(count).setCommodityId(id).setMerchantId(merchantid).setSpecificationId(specificationId).setPrice(price).setCondimentsId(condimentsId)).request(new HttpCallback<PublicMsgBean>(this) {

            @Override
            public void onSucceed(PublicMsgBean data) {
                if (data.getCode()==0){


                    bean.setCount(size);
                    baseViewHolder.setText(R.id.tv_number,size+"");
                    callBackValue.SendMoney(carBean);
                }else {
                    toast(data.getList());
                }
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }
    private void deleteByIds (String id){
        EasyHttp.post(this)
                .api(new DeleteByIdsApi().setIds(id)).request(new HttpCallback<PublicMsgBean>(this) {

            @Override
            public void onSucceed(PublicMsgBean data) {
                if (data.getCode()==0){
                   //刷新列表
                    getOrderList();
                }else {
                    toast(data.getList());
                }
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }
    private int num= 0;
    @Override
    protected void initData() {

    }

    public void showMessageFromActivity(String message,String check){
        id = message;
        page = 1;
        lds.clear();
        checkTv=check;
        getOrderList();
    }
    public void setCheckTv(String checktv){
        checkTv=checktv;
          notAll();
    }
    //全选
    public void checkAll(String checkTv){
        if (carBean.getList().size()>0) {
            if (checkTv.equals("删除")){
            for (int i = 0; i < carBean.getList().size(); i++) {


                    carBean.getList().get(i).setAll(true);
                    for (int j = 0; j < carBean.getList().get(i).getCarts().size(); j++) {
                        carBean.getList().get(i).getCarts().get(j).setAll(true);
                    }

                adapter.notifyDataSetChanged();
                goodsAdp.notifyDataSetChanged();
                callBackValue.SendMoney(carBean);
            }
            }else {
                for (int i = 0; i < carBean.getList().size(); i++) {

                    if (carBean.getList().get(i).getStatusa() == 0) {
                        carBean.getList().get(i).setAll(true);
                        for (int j = 0; j < carBean.getList().get(i).getCarts().size(); j++) {
                            carBean.getList().get(i).getCarts().get(j).setAll(true);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    goodsAdp.notifyDataSetChanged();
                    callBackValue.SendMoney(carBean);
                }
            }
        }else {
            toast("没有商品选择");

        }

    }

    private boolean getSelectAll(){
        List<CarBean.ListDTO> cars = adapter.getData();
        int index = 0;
        for(CarBean.ListDTO car:cars){
            if(car.isAll()){
                index ++;
            }
        }
        if(index == cars.size()){
            return  true;
        }
        return false;
    }
    //全部取消
    public void notAll(){
        if (carBean.getList().size()>0) {
            for (int i = 0; i < carBean.getList().size(); i++) {
                carBean.getList().get(i).setAll(false);
                for (int j = 0; j < carBean.getList().get(i).getCarts().size(); j++) {
                    carBean.getList().get(i).getCarts().get(j).setAll(false);
                }
            }
            adapter.notifyDataSetChanged();
            goodsAdp.notifyDataSetChanged();
            callBackValue.SendMoney(carBean);
        }
    }

    public CallBackCommitValue callBackValue;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //当前fragment从activity重写了回调接口  得到接口的实例化对象
        callBackValue = (CallBackCommitValue) getActivity();
    }
    //定义一个回调接口
    public interface CallBackCommitValue{
        void SendMoney(CarBean car);
        void SelectAll(boolean state);
    }
}
